<?php
$isReloadable = false;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../../_inc/funct.tabDati.php');

if (reqVar('azione') == 'crea') {
	$msgPag = creaRat();
} 

switch(reqVar('azione')) {
	case 'chgMod':
	case 'chgDR':
		$_REQUEST['bil1']='';
	case 'chgB1':
		$_REQUEST['bil2']='';
	case 'chgB2':
		$_REQUEST['bil3']='';
}
reqDef('id_mod_rglob','');
reqDef('bil1','');
reqDef('bil2','');
reqDef('bil3','');

$sqlSel = "SELECT * FROM rgl_azienda " .
		" WHERE id_azienda = ".reqVarAS('id');
$objDB->query($sqlSel,'selRec');
if (!$acAnag = $objDB->fetch('selRec')) {
	backOnErr("rglobIns - var. id '".reqVar('id')."' mancante o errato");
}
$_REQUEST = array_merge($acAnag,$_REQUEST);
reqDef('cod_sett_ratg',reqVar('cod_sett'));

$sSql = "SELECT DISTINCT mg.id_mod_rglob, mg.cod_mod_rglob, mg.descr "
	." FROM rgl_mod_rglob mg "
	." LEFT JOIN rgl_mod_rbil mb ON mb.id_mod_rbil = mg.id_mod_rbil "
	." LEFT JOIN rgl_bilancio bi ON bi.id_set_dati = mb.id_set_dati "
	."    AND id_azienda = ".reqVar('id')
	."    AND stato_lav = 'verificato' "
	." WHERE mg.id_mod_rbil = 0 OR NOT ISNULL(bi.id_bil) " //se previsto mod.bilo. devono esistere bilanci
	." ORDER BY mg.cod_mod_rglob";
$objDB->query($sSql,'selRec');
//dbg_($sSql);
$aModRglob = array(0=>'-- seleziona un modello');
while($acRec = $objDB->fetch('selRec')) {
	$aModRglob[$acRec['id_mod_rglob']] = $acRec['cod_mod_rglob']." - ".$acRec['descr'];
}
if (count($aModRglob)==1) {
	backOnErr('non esitono bilanci verificati');
}
$sqlSel = "SELECT * "
	." FROM rgl_settore ORDER BY cod_sett";
$objDB->query($sqlSel,'selRec');
$aSett = array('***'=>'*** settore generico');
while($acRec = $objDB->fetch('selRec')) {
	$aSett[$acRec['cod_sett']] = $acRec['cod_sett']." - ".$acRec['descr'];
}

$numPeriodi = 0;
if (reqVar('id_mod_rglob') > 0) {
	$sqlSel = "SELECT mg.*,mb.num_periodi, mb.id_set_dati FROM rgl_mod_rglob mg " 
			." LEFT JOIN rgl_mod_rbil mb ON mb.id_mod_rbil = mg.id_mod_rbil "
			." WHERE mg.id_mod_rglob = ".reqVar('id_mod_rglob');
	$objDB->query($sqlSel,'selRec');
	if (!$acRec = $objDB->fetch('selRec')) {
		backOnErr("errore applicativo dati ".$sqlSel);
	}
	$numPeriodi = intval($acRec['num_periodi']);
	$idSetDati = intval($acRec['id_set_dati']);
	
	$sqlSel = "SELECT id_bil,data_rif,descr FROM rgl_bilancio "
		." WHERE stato_lav = 'verificato' "
		."    AND id_azienda = ".reqVar('id')
		."    AND id_set_dati = ".$idSetDati
		." ORDER BY data_rif DESC, id_bil DESC ";
	$objDB->query($sqlSel,'selRec');
	$aBil1 = array(''=>'-- seleziona un bilancio');
	$aDataRif = array();
	while($acRec = $objDB->fetch('selRec')) {
		$aBil1[$acRec['id_bil']] = YMD2DMY($acRec['data_rif'])
			." - ".$acRec['descr'];
		$aDataRif[$acRec['id_bil']] = $acRec['data_rif'];
	}
}
if (reqVar('bil1')>0) {
	$sqlSel = "SELECT id_bil,data_rif,descr FROM rgl_bilancio "
		." WHERE stato_lav = 'verificato' "
		."    AND id_azienda = ".reqVar('id')
		."    AND data_rif < '".$aDataRif[reqVar('bil1')]."' "
		."    AND id_set_dati = ".$idSetDati
		." ORDER BY data_rif DESC, id_bil DESC ";
	$objDB->query($sqlSel,'selRec');
	$aBil2 = array(''=>'-- seleziona un bilancio');
	while($acRec = $objDB->fetch('selRec')) {
		$aBil2[$acRec['id_bil']] = YMD2DMY($acRec['data_rif'])
			." - ".$acRec['descr'];
	}
}
if (reqVar('bil2')>0 && $numPeriodi > 2) {
	$sqlSel = "SELECT id_bil,data_rif,descr FROM rgl_bilancio "
		." WHERE stato_lav = 'verificato' "
		."    AND id_azienda = ".reqVar('id')
		."    AND data_rif < '".$aDataRif[reqVar('bil2')]."' "
		."    AND id_set_dati = ".$idSetDati
		." ORDER BY data_rif DESC, id_bil DESC ";
	$objDB->query($sqlSel,'selRec');
	$aBil3 = array(''=>'-- seleziona un bilancio');
	while($acRec = $objDB->fetch('selRec')) {
		$aBil3[$acRec['id_bil']] = YMD2DMY($acRec['data_rif'])
			." - ".$acRec['descr'];
	}
}

$sCmdR = '';
if (($numPeriodi==2 && reqVar('bil2')>0)
|| (reqVar('bil3')>0)) {
	$sCmdR .= "<a class='cmd1' href=\"javascript:submAz('crea');\">crea</a>";
}
$sCmdR .= cmdTorna('torna');

testaHtml('', $msgPag, 'ratg');
?>
<script type="text/javascript">
<!--
function submAz(az) {
	document.frm1.azione.value = az;
	document.frm1.submit();
}
//-->
</script>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="right">
			<? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo getHtmlForm();
echo getHtmlHidden('azione','...');
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('id');
?>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
	<?=getHtmlRigaRif();?>
   <tr>
      <td class="tit1" colspan='20' align='center'>Creazione rating</td>
   </tr>
<?
$aCamForm = array();
require("../cbil/_inc/const.campiAnag.php");
echo getHtmlCampiForm($aCamForm,'vis');
$aOptChgDR = array("onChange"=>"submAz('chgDR');");
$aOptChgMod = array("onChange"=>"submAz('chgMod');");
$aOptChgB1 = array("onChange"=>"submAz('chgB1');");
$aOptChgB2 = array("onChange"=>"submAz('chgB2');");
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Settore </td>
      <td class="txt1" colspan='16' align='left'>
      	<? echo getHtmlSelect('cod_sett_ratg',$aSett);?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Descrizione</td>
      <td class="txt1" colspan='16' align='left'>
      	<? 
      	echo getHtmlText('descr',80);
      	?> 
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left' valign='top'>Data rif. </td>
      <td class="txt1" colspan='4' align='left' valign='top'>
      	<? 
      	echo getHtmlDate('data_rif','@REQ');
      	?> (facoltativa)
      </td>
      <td class="lab1" colspan='2' align='left' valign='top'>Nota</td>
      <td class="txt1" colspan='10' align='left'>
      	<? 
      	echo getHtmlTextArea('nota',70,3);
      	?> 
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Modello </td>
      <td class="txt1" colspan='16' align='left'>
      	<? echo getHtmlSelect('id_mod_rglob',$aModRglob,'@REQ',$aOptChgMod);?>
      </td>
   </tr>
      	<?
if ($numPeriodi > 0) {
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Bilancio di riferimento </td>
      <td class="txt1" colspan='16' align='left'>
      	<? echo getHtmlSelect('bil1',$aBil1,'@REQ',$aOptChgB1);?>
      </td>
   </tr>
<?
}
if (reqVar('bil1') > 0) {
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Bilancio precedente </td>
      <td class="txt1" colspan='16' align='left'>
      	<? echo getHtmlSelect('bil2',$aBil2,'@REQ',$aOptChgB2);?>
      </td>
   </tr>
<?
}
if ($numPeriodi > 2 && reqVar('bil2') > 0) {
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Bilancio -2 </td>
      <td class="txt1" colspan='16' align='left'>
      	<? echo getHtmlSelect('bil3',$aBil3,'@REQ');?>
      </td>
   </tr>
<?
}
?>
</table>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="right">
			<? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo "</form>\n";

codaHtml();
exit();

function creaRat() {
	global $objDB, $objSess;
	$msg = '';
	$sSql = "SELECT mg.*, mb.cod_mod_rbil, mb.descr AS mb_descr, mb.tipo_tab_indici "
		.", mq.cod_mod_rque, mq.descr AS mq_descr "
		." FROM rgl_mod_rglob mg "
		." LEFT JOIN rgl_mod_rbil mb ON mb.id_mod_rbil = mg.id_mod_rbil "
		." LEFT JOIN rgl_mod_rque mq ON mq.id_mod_rque = mg.id_mod_rque "
		." WHERE mg.id_mod_rglob = ".reqVar('id_mod_rglob')
		;
	$objDB->exec($sSql);
	$aRG = $objDB->fetch();
	$dataRifBil = '';
	if (reqVarInt('bil1')>0) {
		$sSql = "SELECT data_rif FROM rgl_bilancio "
			." WHERE id_bil = ".reqVarInt('bil1')
			;
		$objDB->exec($sSql);
		$aB1 = $objDB->fetch();
		$dataRifBil = $aB1['data_rif'];
	}
	if (reqVar('data_rif')=='' && $dataRifBil!='') {
		$_REQUEST['data_rif'] = YMD2DMY($dataRifBil);
	}
	if (reqVar('data_rif')=='' ) {
		$msg .= 'data rif. mancante';
	}
	if (reqVarStr2date('data_rif')===false) {
		$msg .= 'data rif. errata';
	}
	if ($msg!='') return $msg;
	
	if (reqvarTrim('descr')=='') {
		$sSql = "SELECT descr  FROM rgl_mod_rglob "
			." WHERE id_mod_rglob = ".reqVarInt('id_mod_rglob');
		$objDB->query($sSql, 'readBil');		
		$acX = $objDB->fetch('readBil');
		$_REQUEST['descr'] = $acX['descr'];
	}
	
	$sSql = "INSERT INTO rgl_rating SET id_azienda = ".reqvar('id')
		.", id_mod_rglob = ".reqVar('id_mod_rglob')
		.",cod_sett = '".reqVarAS('cod_sett_ratg')."'"
		.",descr = '".reqVarAS('descr')."'"
		.",nota = '".reqvarAS('nota')."'"
		.",data_ora = '".date('Y-m-d H:i:s')."'"
		.",id_utente = ".$objSess->idUtente
		.",cod_mod_rglob = '".addslashes($aRG['cod_mod_rglob'])."'"
		.",descr_mod_rglob = '".addslashes($aRG['descr'])."'"
		.",data_rif = '".reqVarStr2YMD('data_rif')."' ";
	$objDB->exec($sSql);
	$newIdRat = $objDB->lastInsertId();
	
	if ($aRG['id_mod_rbil']>0) {
		$aVar = array();
		$aDefDati = array();
		$msg = aVarCalcTabDati(reqvarInt('bil1'), reqvarInt('bil2'), $aVar, $aDefDati, 99);		
		$sSql = "INSERT INTO rgl_ratbil SET id_rating = ".$newIdRat
				.", id_mod_rbil = ".$aRG['id_mod_rbil']
				.",id_bil = ".reqvarInt('bil1')
				.",id_bil_2 = ".reqvarInt('bil2')
				.",id_bil_3 = ".reqvarInt('bil3')
				.",peso = ".intval($aRG['peso_rbil'])
				.",tipo_tab_indici = ".intval($aRG['tipo_tab_indici'])
				.",data_ora = '".date('Y-m-d H:i:s')."'"
				.",id_utente = ".$objSess->idUtente
				.",str_def_dati = '".addslashes(gzcser($aDefDati))."'"
				.",str_dati = '".addslashes(gzcser($aVar))."'"
				.",cod_mod_rbil = '".addslashes($aRG['cod_mod_rbil'])."'"
				.",descr_mod_rbil = '".addslashes($aRG['mb_descr'])."'"
				;
		$objDB->query($sSql);
	}
	if ($aRG['id_mod_rque']>0) {
		$sSql = "INSERT INTO rgl_ratque SET id_rating = ".$newIdRat
				.", id_mod_rque = ".$aRG['id_mod_rque']
				.",peso = ".intval($aRG['peso_rque'])
				.",data_ora = '".date('Y-m-d H:i:s')."'"
				.",id_utente = ".$objSess->idUtente
				.",cod_mod_rque = '".addslashes($aRG['cod_mod_rque'])."'"
				.",descr_mod_rque = '".addslashes($aRG['mq_descr'])."'"
				;
		$objDB->query($sSql);
	}
	header("Location: rglobVis.php?id=$newIdRat&xsn=".XSN);
	exit();
}
